package com.farewell.blog.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.farewell.blog.entity.QueryBean;
import com.farewell.blog.exception.NotFoundExcepiton;
import com.farewell.blog.mapper.TypeMapper;
import com.farewell.blog.pojo.Type;
import com.farewell.blog.service.TypeService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author Farewell
 * @date 2021/2/7
 */
@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private TypeMapper typeMapper;


    @Override
    public Type getTypeByName(Type type) {
        return typeMapper.selectOne(type);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public List<Type> getAllTypes() {
        return typeMapper.selectList(new EntityWrapper<>());
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void saveType(Type type) {
        typeMapper.insert(type);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void updateType(Long id, Type type) {
        if (type == null) {
            throw new NotFoundExcepiton("信息为空！");
        }
        type.setId(id);
        typeMapper.updateById(type);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Type getTypeByName(Long id) {
        return typeMapper.selectById(id);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Page<Type> listType(QueryBean queryBean) {
        Page<Type> pageData = new Page<>(queryBean.getCurrentPage(), queryBean.getPageSize());
        EntityWrapper<Type> entityWrapper = new EntityWrapper();
        if (Strings.isNotBlank(queryBean.getQueryString())) {
            entityWrapper.like("name", org.assertj.core.util.Strings.concat("%", queryBean.getQueryString(), "%"));
        }
        List<Type> typeList = typeMapper.listType(pageData);
        pageData.setRecords(typeList);
        return pageData;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void deleteType(Long id) {
        typeMapper.deleteById(id);
    }
}
